package com.highper.common.sehcma;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

import static com.highper.common.constant.SchemaConstant.*;

/**
 * @Author ZhangGJ
 * @Date 2022/01/24 14:52
 */
@Slf4j
public class ContextHandler {

    private static final ThreadLocal<Map<String, String>> DATABASE_THREAD_LOCAL =
            new ThreadLocal<>();

    public static void setSchema(String value) {
        Map<String, String> map = getLocalMap();
        map.put(SCHEMA, value == null || "".equals(value) ? HIGHPER_GATEWAY : value);
        log.info("Switch schema successfully!");
    }

    public static String getSchema() {
        String database = null;
        try {
            Map<String, String> threadLocalMap = DATABASE_THREAD_LOCAL.get();
            if (threadLocalMap == null || threadLocalMap.size() == 0) {
                database = HIGHPER_GATEWAY;
            } else {
                database = threadLocalMap.get(SCHEMA);
            }
        } catch (NullPointerException e) {
            log.error("获取当前租户异常");
            e.printStackTrace();
        }
        return database;
    }

    public static Map<String, String> getLocalMap() {
        Map<String, String> map = DATABASE_THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<>(10);
            DATABASE_THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map<String, String> threadLocalMap) {
        DATABASE_THREAD_LOCAL.set(threadLocalMap);
    }

    public static void remove() {
        DATABASE_THREAD_LOCAL.remove();
    }
}
